﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using shared_libs;
using System.Windows.Forms;
using chatc_application.frame;
using System.Collections;


namespace chatc_application.connect
{
    public class ConnectRemote
    {
        private static ConnectRemote INSTANCE;
        private static IServer_interface obj;
    
        

        private ConnectRemote()
        {
            // Create a channel for cBommunicating w/ the remote object
            // Notice no port is specified on the client
            BinaryServerFormatterSinkProvider serverProv = new BinaryServerFormatterSinkProvider();
            serverProv.TypeFilterLevel = System.Runtime.Serialization.Formatters.TypeFilterLevel.Full;

            BinaryClientFormatterSinkProvider clientProv = new BinaryClientFormatterSinkProvider();

            IDictionary props = new Hashtable();
            props["port"] = 0;

            TcpChannel tcpChannel = new TcpChannel(props, clientProv, serverProv);
            ChannelServices.RegisterChannel(tcpChannel, false);


            // Create an instance of the remote object
            obj = (IServer_interface)Activator.GetObject(
                typeof(IServer_interface),
                "tcp://localhost:8080/chatc_server");

           
        }

        public static ConnectRemote getInstance()
        {
            if (INSTANCE == null)
            {
                INSTANCE = new ConnectRemote();
                return INSTANCE;
            }

            return INSTANCE;
        }
     
       
        public Boolean addNewUser(String user, String password)  
        {
            if (obj.addNewUser(user, password))
            {
                Console.WriteLine("New user" + user + " is created");
                return true;
                
            }
            else
                Console.WriteLine("User already created");
            return false;
        }


        public bool logon(String username, String password, ClientChat cc)
        {

            if (obj.logon(username, password, new MessageReciever(cc, username)))
            {            
                
                return true;
            }
            else
            {
                Console.WriteLine("The user could not be log in");
                return false;
            }
            
        }
        public void sendMessage(String FromUser, String Message)
        {
            obj.sendMessage(FromUser, Message);
        }

        public string getOnlinePeople()
        {
            return obj.getOnlinePeople();
        }
    }

}
